import ExportJsonExcel from "js-export-excel";
import * as XLSX from "xlsx";
import { Button, Upload } from "antd";

const Articles = () => {
  // 导出
  function handleExport() {
    const option: any = {};

    option.fileName = "excel"; // 文件名

    option.datas = [
      {
        sheetData: [
          { one: "一行一列", two: "一行二列" },
          { one: "二行一列", two: "二行二列" },
        ],
        sheetName: "sheet",
        sheetFilter: ["two", "one"],
        sheetHeader: ["第一列", "第二列"],
        columnWidths: [20, 20],
      },
      {
        sheetData: [
          { one: "一行一列", two: "一行二列" },
          { one: "二行一列", two: "二行二列" },
        ],
      },
    ];

    var toExcel = new ExportJsonExcel(option); //new
    toExcel.saveExcel(); //保存
  }

  // 导入
  function beforeUpload(file: any) {
    console.log(file);
    // 创建一个 FileReader 对象
    const reader = new FileReader();
    // 读取文件
    reader.readAsBinaryString(file); // 转成 二进制格式
    //
    reader.onload = function () {
      const workbook = XLSX.read(this.result, { type: "binary" });
      const t = workbook.Sheets["sheet"]; // 拿到表格数据
      // console.log(t)
      const r: any = XLSX.utils.sheet_to_json(t); // 转换成json格式
      console.log(r);
      // 将r的数据上传至服务器
    };

    // 阻止文件上传
    return false;
  }

  return (
    <div>
      <Button onClick={handleExport}>导出</Button>
      <Upload accept=".xlsx" beforeUpload={beforeUpload}>
        <Button>导入</Button>
      </Upload>
    </div>
  );
};

export default Articles;
